package mianshi.leetcode.dp.hard;

public class 编辑距离72 {
    /*

     */
    public int minDistance1(String word1, String word2) {
        int n = word1.length();
        int m = word2.length();

        // 有一个字符串为空串
        if (n * m == 0)
            return n + m;

        // DP 数组
        int[][] D = new int[n + 1][m + 1];

        // 边界状态初始化
        for (int i = 0; i < n + 1; i++) {
            D[i][0] = i;
        }
        for (int j = 0; j < m + 1; j++) {
            D[0][j] = j;
        }

        // 计算所有 DP 值
        for (int i = 1; i < n + 1; i++) {
            for (int j = 1; j < m + 1; j++) {
                int left = D[i - 1][j] + 1;
                int down = D[i][j - 1] + 1;
                int left_down = D[i - 1][j - 1];
                if (word1.charAt(i - 1) != word2.charAt(j - 1))
                    left_down += 1;
                D[i][j] = Math.min(left, Math.min(down, left_down));

            }
        }
        return D[n][m];
    }

    public int minDistance(String word1, String word2) {
        if (word1 == null || word1.equals("")) {
            return word2.length();
        }
        if (word2 == null || word2.equals("")) {
            return word1.length();
        }
        int[][] dp = new int[word1.length() + 1][word2.length() + 2];
        for (int i = 1; i < word1.length() + 1; i++) {
            dp[i][0] = i;
        }
        for (int i = 1; i < word2.length() + 1; i++) {
            dp[0][i] = i;
        }

        int a, b, c;
        for (int i = 1; i < word1.length() + 1; i++) {
            for (int j = 1; j < word2.length() + 1; j++) {
                a = dp[i - 1][j]+1;
                b = dp[i][j - 1]+1;
                c = dp[i - 1][j - 1];
                if (word1.charAt(i-1) != word2.charAt(j-1)) {
                    c++;
                }
                dp[i][j] = Math.min(a, Math.min(b, c));
            }
        }
        return dp[word1.length()][word2.length()];


    }


}
